from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StringType, IntegerType,DoubleType
import pandas as pd
from pyspark.sql import functions as F

# 1用户平均分-DSL(wan)
if __name__ == '__main__':
    # 0. 构建执行环境入口对象SparkSession
    spark = SparkSession.builder.\
        appName("xixi1").\
        getOrCreate()
    sc = spark.sparkContext
    # 1. 读取数据集
    schema = StructType().add("user_id", StringType(), nullable=True). \
        add("movie_id", IntegerType(), nullable=True). \
        add("rank", DoubleType(), nullable=True). \
        add("ts", StringType(), nullable=True)
    df = spark.read.format("csv"). \
        option("sep", "::"). \
        option("header", False). \
        option("encoding", "utf-8"). \
        schema(schema=schema). \
        load("hdfs://node1:8020/input/movie.csv")
    df.groupBy("user_id"). \
        avg("rank"). \
        withColumnRenamed("avg(rank)", "avg_rank"). \
        withColumn("avg_rank", F.round("avg_rank", 2)). \
        write.mode("overwrite"). \
        format("jdbc"). \
        option("url", "jdbc:mysql://node1:3306/bigdata?useSSL=false&useUnicode=true"). \
        option("dbtable", "find_user_garde"). \
        option("user", "root"). \
        option("password", "123456"). \
        save()